﻿@page "/scanqrcode"

@using ZXingBlazor.Components
@using System.Diagnostics

<h3>扫描二维码</h3>

<ul class="list-group">
    <li class="list-group-item">
        <button class="btn btn-primary" type="button" @onclick="OpenBarcodeReader">
            <span class="oi oi-vertical-align-center">ZXingBlazor扫码</span>
        </button>
    </li>
    <li class="list-group-item">
        <button class="btn btn-primary" type="button" @onclick="OpenBarcodeScanner">
            <span class="oi oi-vertical-align-center">BarcodeScanner扫码</span>
        </button>
    </li>

</ul>

@if (ShowScanBarcode)
{
    <BarcodeReader ScanResult="BarcodeReaderOnScanResult"
                   Close="BarcodeReaderOnClose"
                   OnError="BarcodeReaderOnError"
                   ScanBtnTitle="Scan"
                   ResetBtnTitle="Reset"
                   CloseBtnTitle="Close"
                   SelectDeviceBtnTitle="Select Camera" />
}

<div class="m-2">
    <p>扫描结果:</p>
    <p>@Value</p>
</div>

@code {
    private string Value = "";

    //显示扫码界面
    private bool ShowScanBarcode = false;

    private void OpenBarcodeReader()
    {
        Value = "";

        ShowScanBarcode = true;
    }

    private void BarcodeReaderOnScanResult(string result)
    {
        Debug.WriteLine($"扫码结果: {result}");

        Value = result;

        ShowScanBarcode = false;
    }

    private void BarcodeReaderOnClose()
    {
        ShowScanBarcode = false;
    }

    private Task BarcodeReaderOnError(string message)
    {
        Debug.WriteLine($"扫码错误: {message}");

        return Task.CompletedTask;
    }

    private async void OpenBarcodeScanner()
    {
        BarcodeScannerManager.HandleBarcodeResult += BarcodeScannerOnScanResult;

        await BarcodeScannerManager.StartScan();
    }

    private async void BarcodeScannerOnScanResult(object obj, BarcodeScannerResult result)
    {
        Debug.WriteLine($"扫码结果: {result.Result}");

        Value = result.Result;

        BarcodeScannerManager.HandleBarcodeResult -= BarcodeScannerOnScanResult;

        //异步更新UI
        await InvokeAsync(() => StateHasChanged());
    }
}
